#include <stdlib.h>
#include <pthread.h>

#include <iostream>
using std::cout;
using std::endl;

//第四种方案: pthread_once + atexit + destroy
class Singleton
{
public:
    //可以保证多线程安全
    static Singleton * getInstance()
    {   
        pthread_once(&_once, init);
        return _pInstance;
    }

    static void init()
    {
        _pInstance = new Singleton();
        atexit(destroy);
    }
    
    static void destroy()
    {
        if(_pInstance) {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

    int getData() const {   return _data;   }

private:
    Singleton() {   cout << "Singleton()" << endl;  }
    ~Singleton() {  cout << "~Singleton()" << endl;}

private:
    int _data = 0;
    static Singleton * _pInstance;
    static pthread_once_t _once;
};

//初始化操作是在进入main函数之前完成的
Singleton * Singleton::_pInstance = nullptr;//懒汉/饱汉(懒加载)模式
pthread_once_t Singleton::_once = PTHREAD_ONCE_INIT;


void test0()
{
    cout << "test0 method4" << endl;
    Singleton * p1 = Singleton::getInstance();
    Singleton * p2 = Singleton::getInstance();
    cout << "p1:" << p1 << endl;
    cout << "p2:" << p2 << endl;
    cout << p1->getData() << endl;
    cout << p2->getData() << endl;

}


int main()
{
    test0();
    return 0;
}

